package com.promise.jokerdream.network

import com.promise.jokerdream.response.pc.SimplePCResponse
import kotlinx.coroutines.*
import kotlinx.serialization.json.Json
import okhttp3.Call
import okhttp3.Response
import java.io.IOException

/**
 * 支持自动重试的HTTP回调包装器
 * 当响应的result为-2时，会自动重新发起请求
 */
class RetryableHttpCallback(
    private val originalCallback: IHttpCallback,
    private val maxRetries: Int = 10,
    private val retryDelay: Long = 1000L,
    private val retryRequest: () -> Unit
) : IHttpCallback {
    
    private var currentRetryCount = 0
    private val json = Json { 
        ignoreUnknownKeys = true
        encodeDefaults = true
    }
    
    // 使用全局协程作用域，避免内存泄漏
    private val retryScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    
    override fun onSuccess(call: Call, response: Response) {
        try {
            val responseBody = response.body?.string() ?: ""
            
            // 先修复JSON中的非法转义字符，然后解析
            val fixedJson = responseBody.replace(Regex("\\\\[^\"\\\\/bfnrt]"), "\\$1")
            val shouldRetry = try {
                val simpleResponse = json.decodeFromString<SimplePCResponse>(fixedJson)
                simpleResponse.msg == "很抱歉，系统繁忙，请稍后再试!" && simpleResponse.result < 0
            } catch (e: Exception) {
                // 如果修复后仍然无法解析，不进行重试
                println("fixedJson, ${fixedJson}")
                false
            }
            
            if (shouldRetry && currentRetryCount < maxRetries) {
                // 需要重试
                currentRetryCount++
                println("检测到系统繁忙，正在进行第 $currentRetryCount 次重试...")
                
                // 延迟后重新发起请求
                retryScope.launch {
                    delay(retryDelay)
                    retryRequest()
                }
            } else {
                // 不需要重试或已达到最大重试次数，调用原始回调
                if (shouldRetry) {
                    println("已达到最大重试次数($maxRetries)，停止重试")
                }
                
                // 重新创建Response对象，因为body已经被读取
                val newResponse = response.newBuilder()
                    .body(okhttp3.ResponseBody.create(
                        response.body?.contentType(),
                        fixedJson
                    ))
                    .build()
                
                originalCallback.onSuccess(call, newResponse)
            }
            
        } catch (e: Exception) {
            // 处理异常时也调用原始回调
            originalCallback.onSuccess(call, response)
        }
    }
    
    override fun onFailure(call: Call, error: IOException) {
        // 网络请求失败时，可以选择是否重试
        if (currentRetryCount < maxRetries) {
            currentRetryCount++
            println("网络请求失败，正在进行第 $currentRetryCount 次重试: ${error.message}")
            
            // 延迟后重新发起请求
            retryScope.launch {
                delay(retryDelay)
                retryRequest()
            }
        } else {
            // 已达到最大重试次数，调用原始回调
            println("网络请求失败且已达到最大重试次数($maxRetries)，停止重试")
            originalCallback.onFailure(call, error)
        }
    }
    
    /**
     * 重置重试计数器
     */
    fun resetRetryCount() {
        currentRetryCount = 0
    }
}

